import { useState, useEffect } from 'react'
import { message } from 'antd'
// import axios from 'axios'
// import { message } from 'antd'
import { useNavigate } from 'react-router-dom'
import { useSetRecoilState } from 'recoil'
import { platformDetailsInfo } from '@/store/platformDetails'
import { proviencsData } from '@/store/proviencs'
// import { topUserInfo } from '@/store/topUserInfo'
// import { proviencsData } from '@/store/proviencs'
// import { userInfo } from '@/store/userInfo'
import { adminEnum } from '@/store/adminEnumObject'
import { dictValues } from '@/store/dicts'
import { isNullData } from '@/utils'
import { loginRightConfigType, loginInfoType } from '../interface/index'
import { login, getInfo, phoneSearch, dict, getSelectTree } from '../service/service'

export default () => {
  const pushRouter = useNavigate()
  // 这是往 recoil 存对象信息
  const setPlatformDetailsInfo = useSetRecoilState(platformDetailsInfo)
  // 存放顶部管理员所有信息
  // const setTopUserInfo = useSetRecoilState(userInfo)
  // 存放所有管理员的枚举
  const setAdminEnum = useSetRecoilState(adminEnum)
  // 存放三级联动 省市区的数据
  // const setProviencsData = useSetRecoilState(proviencsData)
  const setProviencsData = useSetRecoilState(proviencsData)
  // 存所有的字典
  const setDictValues = useSetRecoilState(dictValues)

  // 用户账号
  const [inputUsername, setInputUsername] = useState<string>('')
  // 根据网址查询查询平台信息
  const [loginInfo, setLoginInfo] = useState<loginInfoType>({} as loginInfoType)
  // 账号下面的管理员
  const [accountAdmins, setAccountAdmins] = useState<any>([])
  // 管理员的下拉框数据二次处理
  const [adminSelect, setAdminSelect] = useState([])
  // 字典的管理员信息 (变成对象，登录下拉框要显示文字)
  const [dictAdminValue, setDictAdminValue] = useState<any>({})
  // 下拉选择管理员的ID
  const [selectId, setSelectId] = useState<number>(0)

  // 登录事件
  const enterLogin = (value: any) => {
    const params = {
      username: value.username,
      password: value.password,
      platformId: loginInfo.platformId,
      accountType: accountAdmins.length < 2 ? accountAdmins[0].accountType : selectId,
    }
    login(params).then(async (res) => {
      if (isNullData(res)) {
        localStorage.setItem('token', res.token)
        message.success('登录成功')

        let accountTypeNumber: number | undefined

        if (accountAdmins.length > 1) {
          accountTypeNumber = selectId
        } else {
          accountTypeNumber = accountAdmins[0]?.accountType
        }

        const redirectTo = accountTypeNumber === 10 ? '/home' : '/resource-zone'
        pushRouter(redirectTo)
      } else {
        message.error(res.msg)
      }
    })
  }
  // 查询某个账号下面有哪些管理员
  const getUserPhoneAdmins = async () => {
    const params = {
      platformId: loginInfo.platformId,
      phone: inputUsername,
    }
    const res = await phoneSearch(params)
    if (res.data.length === 0) {
      message.error('该账号不存在')
      return
    }
    if (isNullData(res)) {
      setAccountAdmins(res.data)
      // 这里处理下拉管理员的数据
      const reconsitution = res.data.reduce((acc: any, cur: any) => {
        acc.push({ id: cur.id, value: cur.accountType, name: dictAdminValue[cur.accountType] })
        return acc
      }, [])

      setAdminSelect(reconsitution)
    }
  }

  // 校验账号
  const validatorUsername = (rele: object, value: string) => {
    const phoneValidator = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
    if (!phoneValidator.test(value)) {
      return Promise.reject('请输入正确的手机号格式!')
    }
    if (!value) {
      return Promise.reject('请输入手机号!')
    }
    if (value && value.includes(' ')) {
      return Promise.reject('手机号不能包含空格!')
    }
    getUserPhoneAdmins()
    return Promise.resolve()
  }

  // 校验密码
  const validatorPassword = (rele: object, value: string) => {
    if (!value) {
      return Promise.reject('请输入密码!')
    }
    if (value && value.includes(' ')) {
      return Promise.reject('密码不能包含空格!')
    }
    return Promise.resolve()
  }

  // 账号的 Input 输入事件
  const usernameChangeValue = (value: any) => {
    setInputUsername(value.target.value)
  }
  // 登录的下拉框拿到 管理员ID
  const selectAdminId = (value: string) => {
    setSelectId(Number(value))
  }

  // 查询平台概况... 以及登录项目的名字 -- 项目 id
  const getPlatformLoginInfo = async () => {
    // const res = await getInfo({ website: window.location.origin })
    const res = await getInfo({ website: 'http://192.168.120.148:8012' })
    // const res = await getInfo({ website: window.location.origin })
    // const res = await getInfo({ website: ''http://192.168.120.148:8012'' })
    // const res = await getInfo({ website: 'www.zj.com' })
    setLoginInfo(res.data)
    console.log('🦢🦢', res.data)
    setPlatformDetailsInfo(res.data)
    localStorage.setItem('platformDetailsInfoSelectValues', JSON.stringify(res.data))
  }

  // 获取字典的管理员数组
  const dictGet = async () => {
    const res = await dict()

    // 存 recoil 所有的字典
    const filat = res.data?.reduce((acc: any, item: any) => {
      const key = Object.keys(item)[0]
      const value = item[key]
      acc[key] = value
      return acc
    }, {})
    setDictValues(filat)

    // 拿到管理员数组
    const platformAccountType = res.data.find((item: {}) => Object.keys(item)[0] === 'platform_account_type')
    const platformAccountTypeValues = platformAccountType.platform_account_type
    // 转换成对象枚举
    const transformedObject = platformAccountTypeValues.reduce((acc: any, item: any) => {
      acc[item.value] = item.label
      return acc
    }, {})
    setAdminEnum(transformedObject)
    setDictAdminValue(transformedObject)
  }

  // 转换三级联动数据结构函数封装
  const convertDataToCascaderFormat = (data: any) =>
    data.map((item: any) => ({
      value: item.id,
      label: item.name,
      children: item.children.length ? convertDataToCascaderFormat(item.children) : [],
    }))

  // 获取省市区三级联动树
  const getProviencsData = async () => {
    const res = await getSelectTree()
    const cascaderData = convertDataToCascaderFormat(res.data)
    setProviencsData(cascaderData)
  }

  useEffect(() => {
    localStorage.removeItem('token')
    dictGet()
    getPlatformLoginInfo()
    getProviencsData()
  }, [])

  const loginRightConfig: loginRightConfigType = {
    enterLogin,
    validatorUsername,
    validatorPassword,
    usernameChangeValue,
    selectAdminId,
    loginInfo,
    accountAdmins,
    adminSelect,
  }

  return {
    loginRightConfig,
  }
}
